package cn.tsvtc.shop.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.tsvtc.shop.constant.CookieConstant;
import cn.tsvtc.shop.constant.RedisConstant;
import cn.tsvtc.shop.entity.LoginUser;
import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.feign.SmsFeign;
import cn.tsvtc.shop.pojo.RegisterEmailUser;
import cn.tsvtc.shop.pojo.RegisterPhoneUser;
import cn.tsvtc.shop.pojo.User;
import cn.tsvtc.shop.service.CodeService;
import cn.tsvtc.shop.service.UserService;
import cn.tsvtc.shop.stream.StreamClient;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: Athena
 * @date: 2020/10/29 17:21
 * @description: 登录相关控制器
 */
@Controller
@RequestMapping("login")
@Slf4j
@CrossOrigin
public class LoginController {

    private StreamClient streamClient;

    private UserService userService;

    private CodeService codeService;

    private RedisTemplate redisTemplate;

    private SmsFeign smsFeign;

    @Autowired
    public LoginController(UserService userService, CodeService codeService, RedisTemplate redisTemplate, SmsFeign smsFeign,StreamClient streamClient){
        this.userService=userService;
        this.codeService=codeService;
        this.redisTemplate=redisTemplate;
        this.smsFeign=smsFeign;
        this.streamClient=streamClient;
    }


    @PostMapping("login.action")
    @ResponseBody
    public ResultMessage<String> login(@CookieValue(name = "cart_token", required = false) String cart_token,
                                       @CookieValue(name = "login_token", required = false) String login_token,
                                       @RequestBody Map map, HttpServletRequest request, HttpServletResponse response){


        ResultMessage<String> login = userService.login(map);
        if(login.getState()){
            //登录成功
            String userLoginedJson = login.getData();
            User userLogined = JSON.parseObject(userLoginedJson, User.class);
            //存入cookie
            Cookie cookie=new Cookie(CookieConstant.LOGIN_TOKEN,login.getMessage());
            String uid=login.getMessage();
            //cookie设置两小时
            cookie.setMaxAge(60 * 60 * 2);
            cookie.setPath("/");
            response.addCookie(cookie);
            login.setData("欢迎回来!"+map.get("uname"));
            //重置message信息
            login.setMessage("success");


            //合并匿名购物车

            if(cart_token!=null){

                StringBuilder stringBuilder=new StringBuilder();
                stringBuilder.append(cart_token);
                stringBuilder.append(":");
                stringBuilder.append(uid);


                streamClient.output().send(MessageBuilder.withPayload(stringBuilder.toString()).build());

                Cookie newcookie = new Cookie("cart_token", null);
                newcookie.setPath("/");
                newcookie.setMaxAge(0);
                response.addCookie(newcookie);
                log.error("login controller stream发送了消息====>"+stringBuilder);
            }
            //合并匿名购物车结束


            return login;
        }else{
            //登录失败
            return login;
        }
    }

    @RequestMapping("status.action")
    @ResponseBody
    public ResultMessage status(@CookieValue(name = "login_token",required = false) String uuid){
        //response.setHeader("Access-Control-Allow-Origin","*");
        log.error("进入statu，你大爷的");
        log.error("uuid====>"+uuid);
        ResultMessage stringResultMessage = new ResultMessage<>();
        //先检查是否有cookie
        if (uuid != null) {
            //有LOGIN_TOKEN，检查登录用户名
            User loginedUser = userService.getStateOfLoginedUser(uuid);
            if (loginedUser != null) {
                //登录成功
                //将没有密码隐私信息的user json返回前端
                //
                log.error("已登录====>"+uuid);
                //LoginUser loginUser = BeanUtil.toBean(loginedUser, LoginUser.class);
                LoginUser loginUser =new LoginUser();
                loginUser.setId(loginedUser.getId());



                loginUser.setPhone(loginedUser.getPhone());//
                loginUser.setEmail(loginedUser.getEmail());//
                loginUser.setUsername(loginedUser.getUsername());

                loginUser.setNickname(loginedUser.getNickname());//
                loginUser.setPic(loginedUser.getPic());
                loginUser.setFlag(loginedUser.getFlag());

                stringResultMessage.setData(loginUser);
                return stringResultMessage;
            }
        }
        log.error("未登录====>"+uuid);
        stringResultMessage.setState(false);
        stringResultMessage.setMessage("failed");
        stringResultMessage.setData("未登录");
        return stringResultMessage;
    }

//    @RequestMapping("logout.action")
//    @ResponseBody
//    public ResultMessage<String> logout(@CookieValue(name = "login_token",required = false) String uuid, HttpServletResponse response){
//
//        ResultMessage stringResultMessage = new ResultMessage<>();
//        Boolean result = userService.logoutByLoginedUser(uuid);
//        //成功从redis中删除
//        Cookie cookie = new Cookie(CookieConstant.LOGIN_TOKEN, "");
//        //重置cookie
//        cookie.setMaxAge(0);
//        cookie.setPath("/");
//        response.addCookie(cookie);
//        stringResultMessage.setState(result);
//        stringResultMessage.setMessage("success");
//        stringResultMessage.setData("已注销");
//        return stringResultMessage;
//    }

    @RequestMapping("logout.action")
    public String logout(@CookieValue(name = "login_token",required = false) String uuid, HttpServletResponse response){
        userService.logoutByLoginedUser(uuid);
        //成功从redis中删除
        Cookie cookie = new Cookie(CookieConstant.LOGIN_TOKEN, "");
        //重置cookie
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "login.html";
    }

}
